package com.mux.java8.list;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;

public class TestList {
	public static void main(String[] args) {
		List<String> list = new ArrayList<String>();
		list.add("aa");
		list.add("bb");
		list.add("cc");
		list.add("adc");
		list.add("abc");
		
		list.forEach(System.out::println);
		
		
		list.stream().filter(s->s.startsWith("a")).forEach(System.out::println);
		System.out.println(Arrays.toString(list.stream().filter(s->s.startsWith("a")).toArray()));
		
		list.stream().sorted().filter(s->s.startsWith("a")).forEach(System.out::println);
		System.out.println(".....");
		list.stream().map(String::toUpperCase).sorted((a,b)->b.compareTo(a)).forEach(System.out::println);
		
		
		Set<String> newList =
		        list.stream()// 1.得到容器的Stream
		        .filter(str -> !Character.isDigit(str.charAt(0)))// 2.选出不以数字开头的字符串
		        .map(String::toUpperCase)// 3.转换成大写形式
		        .collect(Collectors.toSet());
		
		
		System.out.println(".....");
	     Optional<String> reduced = list.stream().sorted().reduce((s1, s2) -> s1 + "#" + s2);
	    // 解释:集合元素排序后->reduce(削减 )->将元素以#连接->生成Optional对象(其get方法返回#拼接后的值)
	    reduced.ifPresent(System.out::println);
	    System.out.println(reduced.get());
	    
	    useParallelStreams();
	}
	
	
	public static  void useParallelStreams() {
        // 初始化一个字符串集合
        int max = 1000000;
        List<String> values = new ArrayList<>();

        for (int i = 0; i < max; i++) {
            UUID uuid = UUID.randomUUID();
            values.add(uuid.toString());
        }

        // 使用顺序流排序

        long sequenceT0 = System.nanoTime();
        values.stream().sorted();
        long sequenceT1 = System.nanoTime();

        // 输出:sequential sort took: 51921 ms.
        System.out.format("sequential sort took: %d ms.", sequenceT1 - sequenceT0).println();

        // 使用并行流排序
        long parallelT0 = System.nanoTime();
        // default Stream<E> parallelStream() {
        // parallelStream为Collection接口的一个默认方法
        values.parallelStream().sorted();
        long parallelT1 = System.nanoTime();

        // 输出:parallel sort took: 21432 ms.
        System.out.format("parallel sort took: %d ms.", parallelT1 - parallelT0).println();

        // 从输出可以看出：并行排序快了一倍多
    }
}
